package ru.exigenservices.intern.dao.hibernate;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.orm.hibernate3.HibernateTemplate;
import ru.exigenservices.intern.dao.ContactDao;
import ru.exigenservices.intern.model.Contact;

import java.util.List;

public class ContactDaoHibernate implements ContactDao {

    public List<Contact> getAll() {
        return hibernateTemplate.loadAll(Contact.class);
    }

    public Contact get(Long id) {
        Contact contact = hibernateTemplate.get(Contact.class, id);
        return contact;
    }

    public Contact delete(Long id) {
        Contact contact = get(id);
        hibernateTemplate.delete(contact);
        return contact;
    }

    public Contact save(Contact contact) {
        hibernateTemplate.saveOrUpdate(contact);
        return get(contact.getId());
    }

    @Required
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

    private HibernateTemplate hibernateTemplate;
    private SessionFactory sessionFactory;

}
